package com.starblink.library.widget.search

import android.content.Context
import android.text.InputFilter
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.Gravity
import android.view.MotionEvent
import android.view.inputmethod.EditorInfo
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import com.google.android.material.textfield.TextInputEditText
import com.starblink.android.basic.ext.color
import com.starblink.android.basic.ext.string
import com.starblink.android.basic.extension.dp2px
import com.starblink.library.widget.R

/**
 * 搜索输入框
 */
class SearchInputView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    styleTheme: Int = 0
) : TextInputEditText(context, attrs, styleTheme) {

    var onCameraIconTap: (() -> Unit)? = null

    var onSearchActionDone: ((text: CharSequence?) -> Unit)? = null

    init {
        setBackgroundResource(R.drawable.bg_search_input)
        hint = string(com.starblink.basic.style.R.string.search_hint)
        setHintTextColor(color(com.starblink.basic.style.R.color.gu_text_disabled))
        textSize = 14f
        setTextColor(color(com.starblink.basic.style.R.color.gu_text_primary))
        requestFocus()
        gravity = Gravity.CENTER_VERTICAL or Gravity.LEFT
        isTextInputLayoutFocusedRectEnabled = true
        setPadding(12.dp2px(), 0, 12.dp2px(), 0)

        imeOptions = EditorInfo.IME_ACTION_SEARCH
        maxLines = 1
        inputType = EditorInfo.TYPE_CLASS_TEXT
        isFocusable = true
        isFocusableInTouchMode = true
        filters = arrayOf(InputFilter.LengthFilter(30))

        val detector =
            GestureDetector(this.context, object : GestureDetector.SimpleOnGestureListener() {

                override fun onSingleTapUp(e: MotionEvent): Boolean {
                    val icon = compoundDrawables[2]
                    if (icon != null && e.x > width - icon.intrinsicWidth - this@SearchInputView.paddingRight) {
                        if ((text?.length ?: 0) > 0) {
                            setText("")
                        }
                        return true
                    }
                    val icon2 = compoundDrawables[0]//相机按钮
                    if (icon2 != null && e.x < icon2.intrinsicWidth + this@SearchInputView.paddingLeft) {
                        onCameraIconTap?.invoke()
                        return true
                    }
                    return super.onSingleTapUp(e)
                }

            })

        setOnTouchListener { _, event ->
            detector.onTouchEvent(event)
        }

        setOnEditorActionListener { _, actionId, _ ->
            if (EditorInfo.IME_ACTION_SEARCH == actionId) {
                onSearchActionDone?.invoke(text)
                true
            } else {
                false
            }
        }

        addTextChangedListener(
            afterTextChanged = {
                switchIcon()
            }
        )
        switchIcon()
    }

    private fun switchIcon() {
        val icon = if ((text?.length
                ?: 0) > 0
        ) ContextCompat.getDrawable(
            this.context,
            R.mipmap.ic_new_close_circle
        ) else null

        val camera = ContextCompat.getDrawable(
            this.context,
            com.starblink.basic.style.R.drawable.ic_svg_camera
        )
        setCompoundDrawablesWithIntrinsicBounds(
            camera,
            null,
            null,
            null
        )

        compoundDrawablePadding = 16.dp2px()
    }

    companion object {

        private const val TAG = "SearchInputView"

        private const val MAX_INPUT_LEN = 30
    }

}